;
var Template = function() {
	"use strict";
	var $modal = $("#category-modal"), $category1 = $("#category1"), $category2 = $("#category2"), $category3 = $("#category3"), $category4 = $("#category4"), $selected;
	var $msg1 = $("#msg1"), $msg2 = $("#msg2"), $msg3 = $("#msg3"), $msg4 = $("#msg4"), $categoryName = $("#category-name"), $categoryId = $("#categoryId");
	var $productInfo = $("#product-info"), $form = $("#template-form"), $grid = $("#menu-list"), $isClothing = $("#is-clothing");
	window.MyDatas = {};
	$("#select-category-btn").click(function() {
		$modal.modal("show").css("display", "table");
	});
	$.ajax({
		type : 'POST',
		url : bsplus.path + "/menu/category",
		success : function(data) {
			if (data && "true" == data.code) {
				var list = data.list;
				if (list && list.length > 0) {
					var lis = [], item;
					for (var i = 0, a = list.length; i < a; i++) {
						item = list[i];
						lis[i] = '<li data-category-id="' + item.categoryId + '" data-isleaf="' + item.isleaf + '" class="category-item" data-level="1" data-name="' + item.nameZh + '"><div class="category-name" title="' + item.nameZh + '（' + item.nameEn + '）">' + item.nameZh + '</div>' + (0 == item.isleaf ? '<span class="menu-icon fa fa-chevron-right"></span>' : '') + '</li>';
					}
					$category1.html(lis.join(""));
				}
			}
		}
	});
	$modal.unbind("click").click(function(e) {
		var $event = e || window.event, $element = $($event.target || $event.srcElement), $li = $element.closest("li.category-item");
		if ($li.length > 0) {
			$selected = $li;
			$li.siblings("li.active").removeClass("active");
			$li.addClass("active");
			var level = $li.data("level"), isleaf = $li.data("isleaf"), $category = $("#category" + (level + 1));
			if (1 == level) {
				$category3.html("").hide();
				$category4.html("").hide();
				$msg1.html($li.data("name"));
				$msg2.html("");
				$msg3.html("");
				$msg4.html("");
			}
			if (2 == level) {
				$category4.html("").hide();
				$msg2.html(" > " + $li.data("name"));
				$msg3.html("");
				$msg4.html("");
			}
			if (3 == level) {
				$msg3.html(" > " + $li.data("name"));
				$msg4.html("");
			}
			if (4 == level) {
				$msg4.html(" > " + $li.data("name"));
			}
			if (1 == isleaf) {
				$category.html("").hide();
			} else {
				$.ajax({
					type : 'POST',
					url : bsplus.path + "/menu/categorys/" + $li.data("category-id"),
					success : function(data) {
						if (data && "true" == data.code) {
							var list = data.list;
							if (list && list.length > 0) {
								var lis = [], item;
								for (var i = 0, a = list.length; i < a; i++) {
									item = list[i];
									lis[i] = '<li data-category-id="' + item.categoryId + '" data-isleaf="' + item.isleaf + '" class="category-item" data-level="' + (level + 1) + '" data-name="' + item.nameZh + '"><div class="category-name" title="' + item.nameZh + '（' + item.nameEn + '）">' + item.nameZh + '</div>' + (0 == item.isleaf ? '<span class="menu-icon fa fa-chevron-right"></span>' : '') + '</li>';
								}
								$category.html(lis.join("")).show();
							}
						}
					}
				});
			}
		}
	});
	return {
		selectCategory : function() {
			if ($selected && $selected.length > 0) {
				if (1 == $selected.data("isleaf")) {
					$categoryName.val(($msg1.html() + $msg2.html() + $msg3.html() + $msg4.html()).replace(/&gt;/g, ">"));
					$modal.modal("hide");
					var categoryId = $selected.data("category-id");
					$categoryId.val(categoryId);
					$form.loading({
						msg : "正在加载数据..."
					});
					$.ajax({
						type : 'POST',
						url : bsplus.path + "/menu/attributeList/" + categoryId,
						success : function(data) {
							$form.unloading();
							console.log(data);
							if (data && "true" == data.code) {
								var list = data.list;
								window.MyDatas = {};
								$productInfo.empty();
								if (list && list.length > 0) {
									var item = null, $html = null, $input = null, $child = null;
									for (var i = 0, a = list.length; i < a; i++) {
										item = list[i];
										$html = $('<div class="form-group"><label class="col-sm-1 control-label">' + (1 == item.required ? '<span class="required">*&nbsp;</span>' : '') + item.nameZh + '</label><div class="col-sm-11"></div></div>');
										$child = $html.find("div.col-sm-11");
										MyDatas[item.arrtNameId] = eval(item.values);
										if ("list_box" == item.attributeShowTypeValue) {
											$input = $('<select class="bsplus-select" data-list="MyDatas[' + item.arrtNameId + ']" data-empty-option="--请选择数据--" data-show-filter="true" name="attr' + item.arrtNameId + '" data-text-field="names.zh" data-value-field="id" data-renderer="Template.renderSelect"></select>')
											$input.data("attr-type", "list_box");
											if (1 == item.required) {
												$input.attr("data-bv-notempty", "");
												$input.attr("data-bv-notempty-message", item.nameZh + "不能为空！");
											}
										} else if ("check_box" == item.attributeShowTypeValue) {
											$input = $('<ul class="attr-list"></ul>');
											var items = MyDatas[item.arrtNameId], html = [], attr;
											if (items && items.length > 0) {
												for (var j = 0, b = items.length; j < b; j++) {
													attr = items[j];
													html[j] = '<li><input data-after-text="' + attr.names.zh + '（' + attr.names.en + '）" type="checkbox" value="' + attr.id + '"></li>';
												}
												$input.append(html.join(""));
											}
											var $in = $('<input class="form-control check-in" name="attr' + item.arrtNameId + '" type="hidden"/>');
											$in.data("attr-type", "check_box");
											if (1 == item.required) {
												$in.attr("data-bv-notempty", "");
												$in.attr("data-bv-notempty-message", item.nameZh + "不能为空！");
											}
											$child.append($in);
										} else if ("input" == item.attributeShowTypeValue) {
											$input = $('<input type="text" class="form-control" name="attr' + item.arrtNameId + '" placeholder="请输入' + item.nameZh + '">');
											$input.data("attr-type", "input");
										} else if ("radio" == item.attributeShowTypeValue) {
											$input = "";
										} else {
											$input = "";
										}
										$child.prepend($input);
										$productInfo.append($html);
									}
									$productInfo.initPlugins();// 初始化插件
									Template.validator();
								}
							} else {
								bsplus.showToast({
									content : "查询数据异常！"
								});
							}
						}
					});
				} else {
					bsplus.showToast({
						content : "您选择的分类含有子类，请选择子类！"
					});
				}
			} else {
				bsplus.showToast({
					content : "请选中产品分类！"
				});
			}
		},
		renderSelect : function(e) {
			return e.record.names.zh + "（" + e.record.names.en + "）";
		},
		submit : function(e) {
			if (!$categoryId.val()) {
				e.preventDefault();
				bsplus.showToast({
					content : "请先选则产品分类！"
				});
			}
		},
		validator : function() {
			var $this = null, $parent = null, vals = null;
			$productInfo.find("input:checkbox").change(function() {
				$this = $(this);
				vals = [];
				$parent = $this.closest("div.col-sm-11");
				$parent.find("input:checkbox:checked").each(function() {
					vals.push(this.value);
				});
				$parent.find("input.check-in").val(vals.join(",")).trigger("input");
			});
			$form.bootstrapValidator({
				excluded : ':disabled',
				message : 'This value is not valid',
				feedbackIcons : {
					valid : 'fa fa-check vicon',
					invalid : 'fa fa-close vicon',
					validating : 'fa fa-refresh vicon'
				}
			}).on('success.form.bv', function(e) {// 表单验证成功
				e.preventDefault();
				var menuId = $("#menuId").val();
				var attrs = {
					id : menuId,
					categoryId : $categoryId.val(),
					categoryName : $categoryName.val(),
					isClothing : $isClothing.prop("checked")
				};
				var index = 0;
				$productInfo.find("input[name],select[name]").each(function() {
					if ("" != this.value) {
						attrs["templates[" + index + "].menuId"] = menuId;
						attrs["templates[" + index + "].attrType"] = $(this).data("attr-type");
						attrs["templates[" + index + "].attrName"] = this.name;
						attrs["templates[" + index + "].attrValues"] = this.value;
						index++;
					}
				});
				$form.loading({
					msg : "正在提交数据..."
				});
				$.ajax({
					url : bsplus.path + "/menu/saveTemplate",
					type : "POST",
					data : attrs,
					success : function(data) {
						$form.unloading();
						if ("true" === data.code) {
							bsplus.showToast({
								content : data.msg,
								backColor : "#51A351"
							});
							$myTab.closeTab("edit-template");
							$grid.reload();
						} else {
							bsplus.showToast({
								content : data.msg,
								backColor : "#C9302C"
							});
						}
					}
				});
			});
		}
	}
}();